/**
 * 上传图片组件
 */

import { message, Upload, UploadProps } from 'antd';
import { UploadChangeParam, UploadFile } from 'antd/lib/upload/interface';
import ImgCrop from 'antd-img-crop';
import { useCallback, useImperativeHandle, useState } from 'react';
import { useRecoilState } from 'recoil';

import { userState } from '../../stores/user';

export interface UploadImageProps extends UploadProps {
  getUrlHandler?: (url: string) => void;
  onRef?: React.MutableRefObject<IUploadImgRefHandler | undefined>;
}

/**向外暴露的重置方法接口 */
export interface IUploadImgRefHandler {
  rest: () => void;
  fill: (urls: string[]) => void;
  getUrls: () => string[]
  files?: UploadFile[]
}

export const UploadImage = ({ getUrlHandler, onRef, maxCount }: UploadImageProps) => {
  const [user] = useRecoilState(userState);

  const [fileList, setFileList] = useState<UploadFile[]>([]);
  /**向外暴露的重置方法 */
  useImperativeHandle(onRef, () => ({
    rest: () => {
      setFileList([]);
    },
    fill: (urls) => {
      const initialArray: UploadFile[] = [];
      urls.forEach((url, index) => {
        initialArray.push({
          uid: '-' + index,
          name: 'avater',
          status: 'done',
          url: url,
        });
      });
      setFileList(initialArray);
    },
    getUrls: () => {
      const urls: string[] = [];
      fileList.forEach(file => {
        console.log(file)
        if (file.url) {
          urls.push(file.url)
        } else if (file.response.data) {
          urls.push(file.response.data)
        }
      })
      return urls;
    }
  }));
  /**上传图片的回调 */
  const onChange = useCallback((info: UploadChangeParam) => {
    if (info.file.status === 'done') {
      if (info.file.response.code === 200) {
        getUrlHandler?.(info.file.response.data);
      } else {
        message.error('上传图片失败');
      }
    }
    setFileList(info.fileList)
  }, []);

  /**上传前的函数钩子 */
  const onPreview = async (file: UploadFile) => {
    let src = file.url;
    if (!src) {
      src = await new Promise((resolve) => {
        const reader = new FileReader();
        reader.readAsDataURL(file.originFileObj as Blob);
        reader.onload = () => {
          resolve(reader.result as string);
        };
      });
    }
    const image = new Image();
    image.src = src || '';
    const imgWindow: any = window.open(src);
    imgWindow.document.write(image.outerHTML);
  };

  /**
   * 删除文件的回到
   */
  const onRemove = useCallback(() => {
    getUrlHandler?.('');
    return true;
  }, []);
  return (
    <ImgCrop modalOk="确认" modalCancel="取消" modalTitle="编辑图片">
      <Upload
        headers={{ token: user?.token || '' }}
        action={'http://81.69.0.39:8082/uploadFile'}
        listType="picture-card"
        fileList={fileList}
        onChange={onChange}
        onPreview={onPreview}
        onRemove={onRemove}
      >
        {fileList.length < (maxCount || 1) && '+ 上传'}
      </Upload>
    </ImgCrop>
  );
};
